<div class="box-page-container">
  <div class="box-page-header">
    <div class="title">Редактирование страницы: <?php echo $this->page->title ?></div>
    <div class="other-controls right">
    </div>
  </div>
  <div class="box-page-body">
    <div class="box-message" id="message" style="display: none"></div>
    <div class="form">
        <dt id="title-label"><label for="title" class="required">Заголовок:</label></dt>
        <dd id="title-element"><input type="text" name="title" id="title" value="<?php echo $this->page->title ?>"></dd>
        <dt id="url-label"><label for="url" class="required">Адресс:</label></dt>
        <dd id="url-element"><input type="text" name="url" id="url" value="<?php echo substr($this->page->url, 6) ?>"><p class="description"><?php echo $this->page->url ?></p></dd>
        <dd id="text-element"><textarea name="text" id="text"><?php echo stripslashes($this->page->text) ?></textarea></dd>
        <h3>Прикрепленные файлы:</h3>
        <ul id="attachment-list" style="display: none"></ul>
        <dd><input name="fileToUpload[]" id="file_upload" class="MultiFile" type="file"/></dd>
    </div>
  </div>
  <div class="box-page-footer">
    <div class="box-controls">
      <div class="right">
       	<div class="btn"><button onclick="save(this); return false;" class="primary">Сохранить</button></div>
      </div>
      <div id="progress" class="progress ajax-preloader-base"></div>
      <div id="control_text" class="box-controls-text"></div>
      <div class="clear-fix"></div>
    </div>
  </div>
  <div class="clear-fix"></div>
</div>
<link rel="stylesheet" href="/css/jquery.cleditor.css" />
<link rel="stylesheet" type="text/css" href="/css/mediaelementplayer.css">
<link rel="stylesheet" type="text/css" href="/css/mejs-skins.css">
<style>
@import url(/css/uploadify.css);
.form input {
  width: 280px;
}
</style>
<script src="/js/jquery/jquery.cleditor.min.js"></script>
<script src="/js/jquery/cleditor/plugins.audio.js"></script>
<script src="/js/jquery/cleditor/plugins.video.js"></script>
<script src="/js/jquery/jquery.uploadify.js"></script>
<script>
$("#text").cleditor({width:'', height:300, useCSS:true, imagePath: '/images/'});
$('#file_upload').uploadify({
	'formData': {'sid': '<?php echo $this->client->sid ?>'},
	'debug'	   : false,
	'buttonText': 'Выбрать файлы...',
	'removeCompleted': true,
	'fileSizeLimit' : '50MB',
	'fileTypeExts' : '*.gif; *.jpg; *.png; *.jpeg; *.mp3; *.avi; *.mp4; *.3gp; *.mpeg; *.txt; *.doc; *.docx; *.xls; *.xlsx; *.ppt; *.pptx; *.rtf; *.pdf; *.rar; *.psd',
    'swf'      : '/js/jquery/uploadify/uploadify.swf',
    'uploader' : '/cp/attachments/upload.attachment',
    'onUploadSuccess' : function(file, data, response) {
        addAttachs($.parseJSON(data));
    }
});
var attachments = <?php echo $this->attachments ?>;
$.each(attachments, function(){
    addAttachs(this);
});
$('.form #url').keyup(function(){
	var val = $(this).val();
	var message = '/page/' + val;
	if (!val) {
		message = '<span style="color: red;">Пожалуйста, укажите адресс страницы!</span>';
	}
	var regexp = /^[a-z0-9_\-\.]*$/i;
	if (!regexp.test(val)) {
		message = '<span style="color: red;">Не верный формат адресса страницы! Только английский алфавит, цифры и знаки "-", "_", "."</span>';
	}
	$('#url-element .description').html(message);
});

$('#file_upload-button').css({
    'height': '20px',
    'line-height': '20px',
    'width': '90px'
});
function addAttachs(data) {
    html = '<li id="'+data.id+'">';
    if (data.type == 'image') {
        html+= '<img src="/images/file-types/image.png" width="16"/ >';
    } else if (data.type == 'doc') {
    	html+= '<img src="/images/file-types/document.png" width="16"/ >';
    } else if (data.type == 'audio') {
    	html+= '<img src="/images/file-types/audio.png" width="16"/ >';
    } else if (data.type == 'video') {
    	html+= '<img src="/images/file-types/video.png" width="16"/ >';
    } else if (data.type == 'other') {
    	html+= '<img src="/images/file-types/other.png" width="16"/ >';
    }
    html+= '<span>' + data.url + '</span>';
    html+= '<span style="float: right;"><a href="' + data.url + '" target="_blank">Открыть</a> <a href="#" onclick="deleteAttach(this, '+data.id+'); return false;">Удалить</a><div id="progress" style="display: none;" class="progress ajax-preloader-base"></div></span>';
    html+= '</li>';
    $('#attachment-list').show().append(html);
}
function deleteAttach(el, id) {
	$(el).parent().find('a').hide().parent().find('#progress').show();
	$.getJSON('/cp/attachments/delete.attach', {'id': id}, function(response){
		if (typeof response.status == 'string' && response.status == 'ok') {
			$(el).parent().parent().remove();
		}
	});
}
var control_text = goog.dom.getElement('control_text');
var progress = goog.dom.getElement('progress');
function save(el) {
    var msgBox = goog.dom.$('message');
    var title = $('.form #title').val();
    var url = $('.form #url').val();
    var text = $('.form #text').val();
    if (!title) {
    	$('.form #title').focus();
    } else if (!url) {
    	$('.form #url').focus();
    }
    if (!title || !url || !text) {
    	msgBox.innerHTML = '<p>Все поля обязательны для заполнения.</p>';
		fx = new goog.fx.dom.FadeInAndShow(msgBox, 200);
		fx.play();
		return false;
    }
	goog.style.showElement(control_text, false);
	goog.style.setStyle(progress, 'display', 'block');
	el.disable = true;
	goog.dom.classes.add(el, 'disabled');
	var attachmentsElements = $('#attachment-list>li');
	var attachments = [];
	if (attachmentsElements.length > 0) {
    	attachmentsElements.each(function(){
        	attachments.push($(this).attr('id'));
        });
	}
	$.ajax({
		"url": "/cp/page/save",
		"type": "POST",
		"dataType": "json",
	    "data": {
	        'id': <?echo $this->page->id ?>,
        	'title': title,
        	'url': url,
        	'text': text,
        	'attachments': attachments
        },
		"success": function(response) {
			goog.style.showElement(control_text, true);
			goog.style.setStyle(progress, 'display', 'none');
			goog.dom.classes.remove(el, 'disabled');
			el.disable = false;
			control_text.innerHTML = 'Страница успешно сохранена.';
			setTimeout(function(){
				goog.style.showElement(control_text, false);
			}, 5000);
		},
		"error": function(response) {
			goog.style.showElement(control_text, true);
			goog.style.setStyle(progress, 'display', 'none');
			goog.dom.classes.remove(el, 'disabled');
			el.disable = false;
			control_text.innerHTML = 'Во время обработки запроса, возникли ошибки.';
			setTimeout(function(){
				goog.style.showElement(control_text, false);
			}, 4000);
		}
	});
}
</script>
